<?php

namespace App\Imports;

use App\Models\FileUserEdit;
use App\Models\User;
use App\Models\UserExtra;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;

class UserEditImport implements ToModel, WithBatchInserts, WithChunkReading, ToArray
{
    private $file;
    private $index = 0;

    /**
     * OrderComparedImport constructor.
     * @param FileGoods|null $file
     */
    public function __construct(FileUserEdit $file = null) {
        $this->file = $file;
    }

    public function array(array $array)
    {
        // TODO: Implement array() method.
        unset($array[0]);
    }

    public function model(array $row)
    {
        // TODO: Implement model() method.
        $this->index++;
        try {
            if ($row[0] == '会员号') {
                return null;
            }
            $model = User::where('number', $row[0])->whereNull('deleted_at')->first();
            if (!$model) {
                throw new \Exception('没有找到对应的用户信息，请检查会员号是否正确');
            }
            $extra = UserExtra::where('user_id', $model->user_id)->first();
            if (isset($row[1]) && $row[1]) {
                if ($row[1] !== '是' && $row[1] !== '否') {
                    throw new \Exception('是否可参与投标字段必须是“是”或“否”');
                }
                $extra->can_bid = $row[1] === '否' ? 0 : 1;
            }
            $extra->save();
            $this->file->increment('success_total');
        } catch (\Throwable $throwable) {
            \DB::table('file_user_edit_error')->insert([
                'file_id' => $this->file->file_id,
                'index' => $this->index,
                'error' => $throwable->getMessage()
            ]);
            $this->file->increment('failure_total');
        }
    }

    public function batchSize(): int
    {
        // TODO: Implement batchSize() method.
        return 1;
    }

    public function chunkSize(): int
    {
        // TODO: Implement chunkSize() method.
        return 1;
    }
}
